import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;

// thread deal with qry
class QueryHandleThread extends Thread {
    private DatagramPacket mPacket;
    private DatagramSocket mSocket;
    private HashMap<String, String> dMap;

    public QueryHandleThread(DatagramPacket packet, DatagramSocket socket, HashMap<String, String> map) {
        super();
        mPacket = packet;
        mSocket = socket;
        dMap = map;
    }

    @Override
    public void run() {
        try {
            RecordMapper rm = new RecordMapper(mPacket, dMap);
            if (rm.isRecorded()) {
                rm.sendResponse(mSocket);
            } else {
                // relay
                dealWithRelay();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public void dealWithRelay() {
        try {
            // new DatagramPacket
            byte[] sendData = buildQryData();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                    InetAddress.getByName("10.3.9.45"), 53);
            mSocket.send(sendPacket);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public byte[] buildQryData() {
        ArrayList<Byte> qryDataAryLst = new ArrayList<Byte>();
        byte[] qryData = mPacket.getData();

        // 中继
        for (int i = 0; i < Integer.parseInt(dMap.get("QNAME_ASS_INDEX")) + 4; i++) {
            qryDataAryLst.add(qryData[i]);
        }

        // 转成数组
        byte[] qryDataAry = new byte[qryDataAryLst.size()];
        for (int i = 0; i < qryDataAryLst.size(); i++) {
            qryDataAry[i] = qryDataAryLst.get(i);
        }
        return qryDataAry;
    }

    public static byte[] binString2ByteAry(String binString) {
        ArrayList<Byte> byteAryLst = new ArrayList<Byte>();
        int byteNum = binString.length() / 8;
        int byteVal = 0;
        int st = 1;
        for (int i = 0; i < byteNum; i++) {
            for (int j = 0; j < 8; j++) {
                if (binString.charAt(8 * i + j) == '1') {
                    for (int k = 0; k < 8 - j - 1; k++) {
                        st = st * 2;
                    }
                    byteVal += st;
                    st = 1;
                }
            }
            byteAryLst.add((byte) byteVal);
            byteVal = 0;
        }
        byte[] byteAry = new byte[byteAryLst.size()];
        for (int i = 0; i < byteAryLst.size(); i++) {
            byteAry[i] = byteAryLst.get(i);
        }
        return byteAry;
    }
}